﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;

namespace Web
{
    public partial class admin_uploadimage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["action"]!=null&&Request.QueryString["action"].ToString()=="upload")
            {
                #region  废弃代码
                //string queryName = Request.QueryString["qqfile"].ToString();
                //string fileName = UploadImage(queryName);
                //if (Request.QueryString["thumb"] != null )
                //{
                //    Size thumbsize = ImageSize(Request.QueryString["thumb"].ToString());
                //    string validateString = ValidateImage(fileName,thumbsize);
                //    if (validateString != "")
                //    {
                //        if (validateString == "-1")
                //        {
                //            Response.Write("{\"error\":\"生成缩略图错误！\"}");
                //            return;
                //        }
                //        else
                //        {
                //            fileName = validateString;
                //        }
                //    }
                //}
                #endregion

                string queryName = Request.QueryString["qqfile"].ToString();
                string fileExt = Request.QueryString["thumb"] == null ? "" : Request.QueryString["thumb"].ToString();
                Size imageSize = ImageSize(fileExt);
                string fileName = UploadImage(queryName, imageSize);
                if (fileName == "-1")
                {
                    Response.Write("{\"error\":\"file upload ext error\"}");
                    return;
                }else if (fileName!="")
                {
                    Response.Write("{\"success\":true,\"filename\":\"" + fileName + "\"}");
                    return;
                }else{
                    Response.Write("{\"error\":\"file upload error\"}");
                    return;
                }
            }
        }

        /// <summary>
        /// 对应不同的页面获取到的图片大小不同
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private System.Drawing.Size ImageSize(string url)
        {
            System.Drawing.Size size = new Size();
            switch(url)
            {
                case "news":
                    size.Width = 130;
                    size.Height = 90;
                    break;
                case "service":
                    size.Width = 188;
                    size.Height = 120;
                    break;
                case "wc":
                    size.Width = 200;
                    size.Height = 200;
                    break;
                case "ilinks":
                    size.Width = 225;
                    size.Height = 225;
                    break;
                case "career":
                    size.Width = 70;
                    size.Height = 70;
                    break;
                default:
                    size.Width = 1280;
                    size.Height = 1024;
                    break;
            }
            return size;
        }



        /// <summary>
        /// 上传图片，超过指定大小之后生成缩略图
        /// 上传成功之后返回文件路径
        /// "-1"代表上传的文件名有问题
        /// ""代表上传失败，出现异常
        /// </summary>
        /// <param name="size"></param>
        /// <returns></returns>
        private string UploadImage(string fileName,Size size)
        {

            #region 图片格式
            //原图图片格式后缀
            int idx = fileName.LastIndexOf('.');
            string fileExt = "";
            if (idx == -1)
            {
                idx = fileName.Length - 3;
                fileExt = "." + fileName.Substring(idx).ToLower();
            }
            else {
                fileExt = fileName.Substring(idx).ToLower();
            }
             
            
            System.Drawing.Imaging.ImageFormat format = null;
            if (fileExt == ".jpg" || fileExt == ".jpeg")
            {
                format = System.Drawing.Imaging.ImageFormat.Jpeg;
            }
            else if (fileExt == ".gif")
            {
                format = System.Drawing.Imaging.ImageFormat.Gif;
            }
            else if (fileExt == ".bmp")
            {
                format = System.Drawing.Imaging.ImageFormat.Bmp;
            }
            else if (fileExt == ".png")
            {
                format = System.Drawing.Imaging.ImageFormat.Png;
            }
            else {
                return "-1";
            }
            #endregion

            string ImageUrlPath = "uploads/"+DateTime.Now.Year+DateTime.Now.Month+"/";//存储文件的文件夹
            string ImageUrl = ImageUrlPath + DateTime.Now.Ticks.ToString() + fileExt;//存储图片的真实地址
            string ImagePath = Server.MapPath("~/" + ImageUrl);//存储图片的真实物理地址
            if (!Directory.Exists(Server.MapPath("~/" + ImageUrlPath)))
            {
                Directory.CreateDirectory(Server.MapPath("~/" + ImageUrlPath));
            }

            //用inputstream生成image对象
            System.Drawing.Image image;
            try
            {
                image = System.Drawing.Image.FromStream(Request.InputStream);
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
                return "";
            }

            #region 按照比例求图片的大小,如果不需要缩略图就直接上传
            //图片大小
            int w = 0,h = 0;
            if (image.Width > size.Width && image.Height > size.Height)
            {
                if (image.Width / image.Height <= size.Width / size.Height)
                {
                    h = size.Height;
                    w = (int)(image.Width * ((float)size.Height / (float)image.Height));
                }
                else
                {
                    w = size.Width;
                    h = (int)(image.Height * ((float)size.Width / (float)image.Width));
                }
            }
            else if (image.Width > size.Width)
            {
                w = size.Width;
                h = (int)(image.Height * ((float)size.Width / (float)image.Width));
            }
            else if (image.Height > size.Height)
            {
                h = size.Height;
                w = (int)(image.Width * ((float)size.Height / (float)image.Height));
            }
            else
            {
                //小于指定尺寸，无需压缩。
                image.Save(ImagePath, format);
                return ImageUrl;
            }
            #endregion

            #region 缩略图 上传图片操作
            //绘制缩略图 
            Bitmap bitmap = new Bitmap(w, h);
            
            Graphics g = Graphics.FromImage(bitmap);
            try
            {
                //设定缩略图呈现质量 
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                //清洁背景 
                g.Clear(Color.Transparent);

                Rectangle thumbRect = new Rectangle(0, 0, w, h);
                g.DrawImage(image, thumbRect);

                //保存缩略图 
                bitmap.Save(ImagePath, format);
            }
            catch(Exception ex)
            {
                Response.Write("graphic save wrong!" + ex.ToString());
                return "";
            }
            finally
            {
                //释放内存 
                bitmap.Dispose();
                image.Dispose();
                g.Dispose();
            }
            return ImageUrl;
            #endregion
        }


        #region 废弃
        private string ValidateImage(string fileName, Size size)
        {
            string isSuccess = "-1";

            //图片缩略图大小
            int w = 0;
            int h = 0;
            System.Drawing.Image image;
            try
            {
                image = System.Drawing.Image.FromStream(Request.InputStream);
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
                return "";
            }
            if (image.Width > size.Width && image.Height > size.Height)
            {
                if (image.Width / image.Height <= size.Width / size.Height)
                {
                    h = size.Height;
                    w = (int)(image.Width * ((float)size.Height / (float)image.Height));
                }
                else
                {
                    w = size.Width;
                    h = (int)(image.Height * ((float)size.Width / (float)image.Width));
                }
            }
            else if (image.Width > size.Width)
            {
                w = size.Width;
                h = (int)(image.Height * ((float)size.Width / (float)image.Width));
            }
            else if (image.Height > size.Height)
            {
                h = size.Height;
                w = (int)(image.Width * ((float)size.Height / (float)image.Height));
            }
            else
            {
                //小于指定尺寸，无需压缩。
                return "";
            }
            //原图图片格式后缀
            int idx = fileName.LastIndexOf('.');
            if (idx == -1)
            {
                return "-1";
            }
            string fileExt = fileName.Substring(idx).ToLower();
            System.Drawing.Imaging.ImageFormat format = null;
            if (fileExt == ".jpg" || fileExt == ".jpeg")
            {
                format = System.Drawing.Imaging.ImageFormat.Jpeg;
            }
            else if (fileExt == ".gif")
            {
                format = System.Drawing.Imaging.ImageFormat.Gif;
            }
            else if (fileExt == ".bmp")
            {
                format = System.Drawing.Imaging.ImageFormat.Bmp;
            }
            else if (fileExt == ".png")
            {
                format = System.Drawing.Imaging.ImageFormat.Png;
            }

            //缩略图路径
            //string dirpath = "uploads";
            //if (!Directory.Exists(dirpath))
            //    Directory.CreateDirectory(dirpath);

            //缩略图
            string thumbImage = "uploads/" + DateTime.Now.Ticks.ToString() + fileExt;
            string thumbPath = Server.MapPath("~/" + thumbImage);

            //绘制缩略图 
            Bitmap bitmap = new Bitmap(w, h);
            Graphics g = Graphics.FromImage(bitmap);
            try
            {
                //设定缩略图呈现质量 
                g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

                //清洁背景 
                g.Clear(Color.White);

                Rectangle thumbRect = new Rectangle(0, 0, w, h);
                g.DrawImage(image, thumbRect);

                //保存缩略图 
                bitmap.Save(thumbPath, format);
            }
            catch
            {
                isSuccess = "-1";
                Response.Write("graphic wrong!");
            }
            finally
            {
                //释放内存 
                bitmap.Dispose();
                image.Dispose();
                g.Dispose();
            }
            isSuccess = thumbImage;
            return isSuccess.ToString();
        }

        private string UploadImage(string fileName)
        {
            if (Request.InputStream != null && Request.InputStream.Length > 0)
            {
                int len = (int)Request.InputStream.Length;
                byte[] bImage = new byte[len];
                Request.InputStream.Read(bImage, 0, len);
                int idx = fileName.LastIndexOf('.');
                string fileEXT = fileName.Substring(idx);
                string newFileName = DateTime.Now.Ticks.ToString() + fileEXT;
                string newFilePath = Server.MapPath("~/uploads/") + newFileName;
                FileStream file = new FileStream(newFilePath, FileMode.Create);
                file.Write(bImage, 0, len);
                file.Close();
                return "uploads/" + newFileName;
            }
            return "";
        }
        #endregion
    }
}
